$(function () {
    init();
    download();
});

function init() {
    // var param = require("../common/getUrlParam").getUrlParam;

    var PDFData = "";
    var currPage = 1; //当前页数从1开始
    var numPages = 0;
    var allNumPages = 0;
    var adjustHeight = 100; //定义滚动到距离页面底部多少像素开始执行方法
    var _scrollHeight = $(document).height(); //获取文档的高度
    var _windowHeight = $(window).height(); //获取可视窗口的高度
    var _scrollTop = $(window).scrollTop(); //获取windeow滚动的高度
    var _switch = false;
    var highPull = function (cb) {
        _scrollTop = $(window).scrollTop();
        if (_scrollHeight - adjustHeight < _scrollTop + _windowHeight && _scrollHeight != _windowHeight) {
            if (cb) cb();
        };
    };
    // var pdfFile = encodeURI(getUrlParam("pdfFile"));
    var pdfFile = getUrlParam("pdfFile");
    
    if (pdfFile) {
        $.ajax({
            type: "get",
            mimeType: 'text/plain; charset=x-user-defined',
            //url:'http://app.xiaozhibaoxian.com/uat-fsite//document/download?fileCode=116283256c15491c8a3f3b9eb599cf54',
            url: pdfFile,
            success: function (data) {
                if (data) {
                    $(".toolbarButton").show();
                    // var sub = data.substring(0, 40);
                    PDFData = data;
                    if (PDFData) {
                        var rawLength = PDFData.length;
                        //转换成pdf.js能直接解析的Uint8Array类型,见pdf.js-4068
                        var array = new Uint8Array(new ArrayBuffer(rawLength));
                        for (i = 0; i < rawLength; i++) {
                            array[i] = PDFData.charCodeAt(i) & 0xff;
                        }
                        PDFJS.getDocument(array).then(function (pdf) {
                            // require('module/common/dialog').hideLoading();

                            //获取一共有多少页
                            allNumPages = pdf.numPages;
                            //allNumPages=7;
                            numPages = 3;

                            var showPage = '1-3';
                            if (allNumPages == 1) {
                                showPage = '1';
                                $("#nextPage").attr("disabled", "disabled");
                                pdf.getPage(1).then(handlePages);
                            } else if (allNumPages > 1 && allNumPages <= 3) {
                                showPage = '1-' + allNumPages;
                                $("#nextPage").attr("disabled", "disabled");
                                for(var p = 0; p < allNumPages; p++){
                                    pdf.getPage(p+1).then(handlePages);
                                }
                                // pdf.getPage(1).then(handlePages);
                                // pdf.getPage(2).then(handlePages);
                            } else if (allNumPages > 3) {
                                //从第一页开始
                                for (var i = 0; i < 3; i++) {
                                    pdf.getPage(i + 1).then(handlePages);
                                }
                            }
                            $("#pages").text(showPage + ' / 共' + allNumPages + '页')
                            $("#nextPage").show().click(function () {
                                $(window).scrollTop(0);
                                for (var i = 0; i < 3; i++) {
                                    $("#canvasCon_" + (currPage - 3 + i)).remove();
                                }
                                $("#prePage").removeAttr("disabled");
                                if (currPage + 2 < allNumPages) {
                                    // require('module/common/dialog').showLoading('加载中');

                                    //将pdf对象赋值到全局变量，能够在其他方法中使用
                                    for (i = 0; i < 3; i++) {
                                        pdf.getPage(currPage + i).then(handlePages);
                                    }
                                    showPage = currPage + '-' + (currPage + 2);

                                } else if (currPage + 2 == allNumPages) {
                                    $(this).attr("disabled", "disabled");
                                    // require('module/common/dialog').showLoading('加载中');

                                    for (i = 0; i < 3; i++) {
                                        pdf.getPage(currPage + i).then(handlePages);
                                    }
                                    showPage = allNumPages - 2 + '-' + allNumPages;

                                } else {
                                    $(this).attr("disabled", "disabled");
                                    for (i = 0; i <= allNumPages - currPage; i++) {
                                        pdf.getPage(currPage + i).then(handlePages);
                                    }
                                    showPage = currPage + '-' + allNumPages;
                                    if (currPage == allNumPages) {
                                        showPage = allNumPages;
                                    }
                                }
                                $("#pages").text(showPage + '/ 共' + allNumPages + '页')

                            });
                            $("#prePage").click(function () {
                                $(window).scrollTop(0);
                                for (var i = 0; i < 3; i++) {
                                    $("#canvasCon_" + (currPage - 3 + i)).remove();
                                }
                                $("#nextPage").removeAttr("disabled");
                                if (currPage - 6 == 1) {
                                    $(this).attr("disabled", "disabled");
                                    currPage = 1;
                                    showPage = '1-3';
                                } else if (currPage > allNumPages) {
                                    var p = allNumPages % 3 > 0 ? 3 : 6
                                    currPage = currPage - allNumPages % 3 - p;
                                    showPage = currPage + '-' + (currPage + 2);
                                } else {
                                    currPage = currPage - 6;
                                    showPage = currPage + '-' + (currPage + 2);
                                }
                                // require('module/common/dialog').showLoading('加载中');

                                for (i = 0; i < 3; i++) {
                                    pdf.getPage(currPage + i).then(handlePages);
                                }
                                $("#pages").text(showPage + '/ 共' + allNumPages + '页')
                            })
                        });
                    }

                } else {
                    // require('module/common/dialog').hideLoading();
                    // require('module/common/dialog').showToast("pdf请求失败");
                    console.log('请求失败!');
                }
            },
            error: function (res) {
                console.log(res)
            }
        });
    } else if (getUrlParam("pdf2png")) {
        setTimeout(function () {
            // require('module/common/dialog').hideLoading();
        }, 2000)
        $("#content").append("<img class='pdfImg' src='" + param("pdf2png") + "'>")
    }

    function handlePages(page) {
        //获取全尺寸pdf
        var viewport = page.getViewport(2);
        var canvas = document.createElement("canvas");
        var canvasCon = document.createElement("div");
        canvas.id = "canvas_" + currPage;
        canvasCon.id = "canvasCon_" + currPage;
        canvasCon.className = "canvasCon";
        var winRatio = ($(window).width() / viewport.width) * 0.9;
        $(canvas).css({
            "transform": "scale(" + winRatio + ")",
            "webkitTransform": "scale(" + winRatio + ")",
            "left": $(window).width() * 0.05
        });
        $(".canvasCon").css({
            'height': viewport.height * winRatio
        });
        var context = canvas.getContext('2d');
        canvas.height = viewport.height;
        canvas.width = viewport.width;
        //在canvas上绘制
        page.render({
            canvasContext: context,
            viewport: viewport
        });
        //在页面中插入画布
        document.getElementById("content").appendChild(canvasCon);
        document.getElementById("canvasCon_" + currPage).appendChild(canvas);
        // require('module/common/dialog').hideLoading();

        //开始下一页到绘制
        currPage++;
        //if ( thePDF !== null && currPage <= numPages ) {
        //    thePDF.getPage( currPage ).then( handlePages );
        //}
    }
}

function download(){
    $("#download").click(function () {
        // var data = require('module/common/browser');
        downloadDialog();
        //ios 微信打开
        if (browser.versions.iPhone && browser.versions.weixin) {
            // require('module/common/dialog').downloadDialog();
            downloadDialog();
        } else {
            // window.location.href = "doc/" + getUrlParam("pdfFile") + "&appDownload=true";
            var pdfFile = getUrlParam("pdfFile");
            var downUrl = $('<a href="doc/'+ pdfFile +'" download="test.pdf">'+ pdfFile +'</a>')[0];
            downUrl.click();
        }

    });
}

function downloadDialog(){
    var html='<div class="js_dialog downloadDialog" id="iosDialog2">'
        +'<div class="weui-mask"></div>'
        +'<div class="weui-dialog">'
        +'<div class="weui-dialog__bd">'
            +'<div class="weui-dialog-img"> </div>'
            +'<div class="white f32 weui-dialog-content mt50">'
                +'<p>点击右上角</p>'
                +'<p>选择“在Safari中打开”</p>'
            +'</div>'
        +'</div>'
        +'</div>'
    '</div>';
    $('body').append(html);
    
    $('body').undelegate('.downloadDialog','click');
    $('body').delegate('.downloadDialog','click',function(){
        $('.downloadDialog').remove();
    });
}

function getUrlParam(name) { //一个获取url中参数的方法
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg); //匹配目标参数
    if (r != null) return unescape(r[2]);
    return null; //返回参数值
};

browser={
    versions:function(){
        var u = navigator.userAgent, app = navigator.appVersion;
        return {
            trident: u.indexOf('Trident') > -1, //IE内核
            presto: u.indexOf('Presto') > -1, //opera内核
            webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
            gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1,//火狐内核
            mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
            ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
            android: u.indexOf('Android') > -1 || u.indexOf('Adr') > -1, //android终端或者uc浏览器
            iPhone: u.indexOf('iPhone') > -1 , //是否为iPhone或者QQHD浏览器
            iPad: u.indexOf('iPad') > -1, //是否iPad
            webApp: u.indexOf('Safari') == -1, //是否web应该程序，没有头部与底部
            weixin: u.indexOf('MicroMessenger') > -1, //是否微信 
            isQQ: u.match(/\sQQ/i) == "qq", //是否QQ
            qq:u.indexOf('QQ')>-1
        };
    }(),
    language:(navigator.browserLanguage || navigator.language).toLowerCase()
}